
package com.eorchis.module.news.service.impl;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.eorchis.core.basedao.dao.IDaoSupport;
import com.eorchis.core.basedao.entity.IBaseEntity;
import com.eorchis.core.service.impl.AbstractBaseService;
import com.eorchis.module.basedata.domain.BaseData;
import com.eorchis.module.basedata.domain.BaseDataCondition;
import com.eorchis.module.basedata.service.IBaseDataService;
import com.eorchis.module.blob.domain.BaseBlob;
import com.eorchis.module.blob.service.impl.BlobServiceImpl;
import com.eorchis.module.news.dao.INewsDao;
import com.eorchis.module.news.domain.News;
import com.eorchis.module.news.domain.NewsQueryBean;
import com.eorchis.module.news.domain.ReceiveUserQueryBean;
import com.eorchis.module.news.service.INewsService;
import com.eorchis.module.news.ui.commond.NewsQueryCommond;
import com.eorchis.module.news.ui.commond.NewsValidCommond;
import com.eorchis.module.newsuserlink.service.INewsUserLinkService;
import com.eorchis.module.newsuserlink.ui.commond.NewsUserLinkValidCommond;
import com.eorchis.module.remind.domain.RemindUser;
import com.eorchis.module.trainingclass.service.ITrainingClassService;
import com.eorchis.module.trainingclass.ui.commond.TrainingClassValidCommond;
import com.eorchis.module.util.UnitConvertUtil;
import com.eorchis.utils.utils.PropertyUtil;

/**
 * Title: NewsServiceImpl<br>
 * Description: 消息管理管理业务接口实现<br>
 * Company: GoldGov<br>
 * Copyright @ 2012 GoldGov .All rights reserved.<br>
 * @author RongSL
 * @createDate 2016-05-06
 * @version $Revision$
 */
// 声明本类为Server实现类，声明bean名称
@Service(value = "com.eorchis.module.news.service.impl.NewsServiceImpl")
public class NewsServiceImpl extends AbstractBaseService implements INewsService {

	@Resource(name = "com.eorchis.module.news.dao.impl.NewsDaoImpl")
	private INewsDao newsDao;
	// 消息用户关联表接口
	@Resource(name = "com.eorchis.module.newsuserlink.service.impl.NewsUserLinkServiceImpl")
	private INewsUserLinkService newsUserLinkService;
	//附件
	@Autowired
	@Qualifier("com.eorchis.module.blob.service.impl.BlobServiceImpl")
	private BlobServiceImpl blobServiceImpl;
	//数据字典
	@Resource(name = "com.eorchis.module.basedata.service.impl.BaseDataServiceImpl")
	private IBaseDataService baseDataService;
	//培训班
	@Autowired
	@Qualifier("com.eorchis.module.trainingclass.service.impl.TrainingClassServiceImpl")
	private ITrainingClassService trainingClassService;
	@Override
	public IDaoSupport getDaoSupport() {
		return newsDao;
	}

	@Override
	@SuppressWarnings("unchecked")
	public NewsValidCommond toCommond(IBaseEntity entity) {
		return new NewsValidCommond((News)entity);
	}
	/**
	 * 查询未选接收人列表
	 * @param qCommond
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @createDate 2016-5-10
	 */
	@Override
	public List<ReceiveUserQueryBean> findNoSelectedReceiveUserList(
			NewsQueryCommond qCommond) throws Exception {
		return newsDao.findReceiveUserList(qCommond);
	}
	/**
	 * 查询已选接收人列表
	 * @param qCommond
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @createDate 2016-5-10
	 */
	@SuppressWarnings({ "null", "unchecked" })
	@Override
	public List<ReceiveUserQueryBean> findSelectedReceiveUserList(
			NewsQueryCommond qCommond) throws Exception {
		//判断前端是否传入已选人员ids,如果没有传入说明是第一次点开这个列表，需要查一下已接收人ids
		if(!PropertyUtil.objectNotEmpty(qCommond.getSearchSelectedUserIds())){
			String[] selectedUserIds = null;
			List<NewsUserLinkValidCommond> list=(List<NewsUserLinkValidCommond>) newsUserLinkService.findAllList(qCommond);
			for(int i=0;i<list.size();i++){
				selectedUserIds[i]=list.get(i).getUserId();
			}
			qCommond.setSearchSelectedUserIds(selectedUserIds);
		}
		return newsDao.findReceiveUserList(qCommond);
	}
	/**
	 * 上传附件
	 * @param commond
	 * @param request
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @date 2016-5-11
	 */
	@Override
	public NewsValidCommond uploadNewsFile(NewsValidCommond commond, HttpServletRequest request) throws Exception{
		//上传
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		boolean flag = true;
		try {
			for (MultipartFile mf : fileMap.values()) {
				CommonsMultipartFile cmf = (CommonsMultipartFile) mf;
				FileItem item = cmf.getFileItem();
				String msg ="";
				if (!item.isFormField()) {
					String name = item.getName();
					if (name == null || name.trim().equals("")||mf.getBytes().length==0) {
						msg = "上传失败!上传文件为空!";
						commond.setMessage(msg);
//						flag = false;
					}else {
						byte[] bytes = mf.getBytes();
						BaseBlob bb = new BaseBlob();
						String attName = name.substring(0,name.lastIndexOf("."));
						bb.setAttName(attName);
						String fileType = name.substring(name.lastIndexOf("."));
						bb.setAttExt(fileType);
						bb.setAttBlob(Hibernate.createBlob(bytes));
						
						//获取文件大小单位字节  1G=1024MB  1MB=1024KB 1KB=1024字节 1个汉字占两个字节.
						Double size=(double) item.getSize()/1024/1024;
						DecimalFormat    df   = new DecimalFormat("######0.00"); 
						String sizeStr=df.format(size);
						size=Double.valueOf(sizeStr).doubleValue(); 
						if(PropertyUtil.objectNotEmpty(size)&&size>30){
							msg = "上传失败!上传文件大小不能超过30MB!";
							commond.setMessage(msg);
							flag =false;
							commond.setFlag(flag);
							return commond;
						}
						blobServiceImpl.addBlob(bb);
						commond.setAttachmentId(bb.getBlobID());
						commond.setFileSize(UnitConvertUtil.getPrintSize(item.getSize()));
						commond.setMessage("上传成功!");
					}
				}
			}
		}catch (Exception e){
			commond.setMessage("上传失败!");
			flag =false;
		}
		if(commond.getMessage() == null || "".equals(commond.getMessage())){
			commond.setMessage("上传失败!");
			flag =false;
		}
		commond.setFlag(flag);
		return commond;
	}
	
	/**
	 * 新增消息
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @date 2016-4-21
	 */
	@Override
	public void addNews(NewsValidCommond commond) throws Exception{
		//消息类型
		if(PropertyUtil.objectNotEmpty(commond.getNewsTypeCode())){
			BaseDataCondition condition = new BaseDataCondition();
			condition.setSearchDataCode(commond.getNewsTypeCode());
			BaseData newsType=baseDataService.viewBaseData(condition);
			if(PropertyUtil.objectNotEmpty(newsType)){
				commond.setNewsType(newsType);
			}
		}
		//培训班名称
		if(PropertyUtil.objectNotEmpty(commond.getSearchClassID())){
			TrainingClassValidCommond tcommond=trainingClassService.find(commond.getSearchClassID());
			if(PropertyUtil.objectNotEmpty(tcommond.getClassName())){
				commond.setClassName(tcommond.getClassName());
			}
		}
		commond.setSendLookState(News.IS_Y);//发送人显示状态:显示
		commond.setActiveState(News.IS_Y);//活动
		commond.setCreateDate(new Date());
		this.save(commond);	
		//保存消息接收人关联表数据
		News news=newsDao.find(News.class, commond.getEntityID());
		news.setNewsId(commond.getNewsId());
		if(PropertyUtil.objectNotEmpty(commond.getReceiveUserId()) && PropertyUtil.objectNotEmpty(commond.getReceiveUserId()[0])){
			for(String userId : commond.getReceiveUserId()[0].split(",")){
				NewsUserLinkValidCommond c=new NewsUserLinkValidCommond();
				c.setReadState(News.IS_N);//未读取
				c.setReplyState(News.IS_N);//未回复
				c.setActiveState(News.IS_Y);//活动
				c.setReceiveLookState(News.IS_Y);//显示
				c.setNewsId(news);
				c.setCreateDate(new Date());
				c.setUserId(userId);
				newsUserLinkService.save(c);
			}
		}
	}

	@Override
	public List<ReceiveUserQueryBean> findBlobList(String blobId)
			throws Exception {
		return newsDao.findBlobList(blobId);
	}
	/**
	 * 查询接收人ID及姓名
	 * @param commond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @date 2016-5-11
	 */
	@Override
	public NewsValidCommond findReceiveUser(NewsValidCommond commond)
			throws Exception {
		return newsDao.findReceiveUser(commond);	
	}
	
	/**
	 * 查询委托部委管理员
	 * @Date 2016-05-13
	 * @author RongSL
	 * */
	@Override
	public List<RemindUser> findAdministrator(NewsQueryCommond commond)throws Exception{
		return newsDao.findAdministrator(commond);
	}
	
	/**
	 * 查询消息列表
	 * @return
	 * @throws Exception
	 * @author LongJZ
	 * @createDate 2016-6-21
	 */
	public List<NewsQueryBean> findNewsList(NewsQueryCommond queryCommond) throws Exception {
		return newsDao.findNewsList(queryCommond);
	}
	
	
	
	/**
	 * 未读消息数
	 * @return
	 * @throws Exception
	 * @author GUOLEI
	 * @createDate 2016-6-21
	 */
	@Override
	public Integer receiveNewsCount(NewsValidCommond validCommond) throws Exception {
		return newsDao.receiveNewsCount(validCommond);
	}
	
	

	/**
	 * 接收消息列表
	 * @return
	 * @throws Exception
	 * @author GUOLEI
	 * @createDate 2016-6-21
	 */
	@Override
	public List<NewsQueryBean> replyNewsUserList(NewsQueryCommond queryCommond) throws Exception {
		return newsDao.replyNewsUserList(queryCommond);
	}
	
	
	/**
	 * 查询回复消息人员列表
	 * @return
	 * @throws Exception
	 * @author GUOLEI
	 * @createDate 2016-6-21
	 */
	@Override
	public List<NewsQueryBean> findReplyUserList(NewsQueryCommond queryCommond) throws Exception {
		return newsDao.findReplyUserList(queryCommond);
	}
	
	
	/**
	 * 回复消息列表
	 * @return
	 * @throws Exception
	 * @author GUOLEI
	 * @createDate 2016-6-21
	 */
	@Override
	public List<NewsQueryBean> findReplyNewsList(NewsQueryCommond queryCommond) throws Exception {
		return newsDao.findReplyNewsList(queryCommond);
	}
	
	/**
	 * 回复消息列表
	 * @return
	 * @throws Exception
	 * @author GUOLEI
	 * @createDate 2016-6-21
	 */
	@Override
	public NewsQueryBean findReplyNews(NewsValidCommond validCommond) throws Exception {
		return newsDao.findReplyNews(validCommond);
	}
	
	/**
	  * @修改接收人显示状态
	  * @Name: updateReceiveLookStata
	  * @Description: @return
	  * @Author: GUOLEI
	  * @Version: V1.00
	  * @Create Date: 2016-6-24上午10:45:26
	  * @Parameters: NewsDaoImpl
	  * @Return: String
	 */
	@Override
	public String  updateReceiveLookStata(NewsValidCommond validCommond){
		return newsDao.updateReceiveLookStata(validCommond);
	}

	
	/**
	  * @修改发送人显示状态
	  * @Name: updateSendLookStata
	  * @Description: @return
	  * @Author: GUOLEI
	  * @Version: V1.00
	  * @Create Date: 2016-6-24上午10:45:35
	  * @Parameters: NewsDaoImpl
	  * @Return: String
	 */
	@Override
	public String  updateSendLookStata(NewsValidCommond validCommond){
		return newsDao.updateSendLookStata(validCommond);
	}
	
	
	/**
	  * @修改读取状态
	  * @Name: addReply1
	  * @Description: @param validCommond
	  * @Description: @return
	  * @Author: GUOLEI
	  * @Version: V1.00
	  * @Create Date: 2016-6-24下午2:07:06
	  * @Parameters: NewsDaoImpl
	  * @Return: String
	 */
	@Override
	public String  updateReadState(NewsValidCommond validCommond){
		return newsDao.updateReadState(validCommond);
	}
	
	
	/**
	 * 添加消息回复
	 * @throws Exception
	 * @author GUOLEI
	 * @createDate 2014-5-14
	 */
	@Override
	public Boolean addReply(NewsValidCommond validCommond)throws Exception {
		 newsDao.updateSendLookStata(validCommond);
		 newsDao.updateReceiveLookStata(validCommond);
		return newsDao.addReply(validCommond);
	}

	/**
	 * 查询消息列表
	 * @return
	 * @throws Exception
	 * @author LongJZ
	 * @createDate 2016-6-21
	 */
	@Override
	public void updateReplyReadStata(NewsQueryCommond queryCommond) throws Exception {
		newsDao.updateReplyReadStata(queryCommond);
	}
}
